/**   
 * @Title: BootBroadcastReceiver.java 
 * @Package com.atsmart.app.service 
 * @Description: 
 * @author 刘三辉
 * @date 2012-5-12 上午11:13:00 
 * @version V1.0   
 */
package com.atsmart.app.receiver;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.util.Log;

import com.atsmart.app.BizApp;
import com.atsmart.app.R;
import com.atsmart.app.activity.LoginActivity;
import com.atsmart.app.model.CheckDurationInfo;
import com.atsmart.app.model.CommonBody;
import com.atsmart.app.model.PositionAttributeInfo;
import com.atsmart.app.model.PositionInfo;
import com.atsmart.app.model.PositionShutDownInfo;
import com.atsmart.app.model.PositonsInfo;

import com.atsmart.app.service.CheckingService;
import com.atsmart.app.sql.NumberSqlHelper;
import com.atsmart.app.sql.PositionSqlHelper;
import com.atsmart.app.sql.ShutDownSqlHelper;
import com.atsmart.app.utils.LocationUtils;
import com.atsmart.app.utils.StringUtil;
import com.atsmart.app.webservice.ServiceHelper;
import com.atsmart.app.webservice.ServiceHost;
//import com.atsmart.log.UserLog;
import com.google.json.Gson;

/**
 * @ClassName: BootBroadcastReceiver
 * @Description: 开关机
 * @author 刘三辉
 * @date 2012-5-12 上午11:13:01
 */
public class BootBroadcastReceiver extends BroadcastReceiver {


	TimerTask tt;
	Timer time;

	private boolean start = false;
	private boolean end = false;
	private NumberSqlHelper nsql = null;

	//
	@Override
	public void onReceive(final Context context, Intent intent) {
//		UserLog.getInstance().writelocal("开机了 : time： = " + StringUtil.getCurrentTime());
		if (!BizApp.getInstance().isServiceRun()) {
			
			Intent i = new Intent(context, CheckingService.class);
			context.startService(i);
		}
		if (checkSheetTime()) {
			time = new Timer();
			tt = new TimerTask() {
				public void run() {
					start_end();
				}
			};

			time.schedule(tt, 40 * 1000);
		}

	}

	//
	public void saveToSDCard(String filename, String content) throws Exception {
		// Environment.getExternalStorageDirectory()��ʾ�ҵ�sdcarfĿ¼
		File file = new File(Environment.getExternalStorageDirectory(),
				filename);
		FileOutputStream outStream = new FileOutputStream(file, true);
		outStream.write(content.getBytes());
		outStream.close();
	}

	private void start_end() {
		try {
			new Thread() {
				public void run() {
					Gson gson = new Gson();
					CommonBody body = new CommonBody();
					body.setCommand(2);
					body.setImsi(BizApp.getInstance().getIMSI());
					body.setVersion(BizApp.getInstance().getString(
							R.string.app_version));

					PositonsInfo positions = new PositonsInfo();
					positions.positions = new ArrayList<PositionInfo>();
					PositionInfo position = new PositionInfo();
					position.date = StringUtil.millToDate(Calendar
							.getInstance().getTimeInMillis());

					boolean ff = false;
					if ((BizApp.getInstance().isWiFiActive() || BizApp
							.getInstance().isNetworkAvailable())
							&& BizApp.getInstance().keeping) {
						if (BizApp.getInstance().getCurrentLocation() == null
								|| BizApp.getInstance().getLat() < 0.0001
								|| BizApp.getInstance().getLon() < 0.0001
								|| System.currentTimeMillis() > (BizApp
										.getInstance().getLocTime() + 70000)) {
							if (!BizApp.getInstance()
									.getmLocationClient().isStarted()) {
								BizApp.getInstance()
										.getmLocationClient().start();
							}
							try {
								Thread.sleep(7000);
								int i = 0;
								while (!BizApp.getInstance().isLocation
										&& i < 11) {
									sleep(4000);
									// Log.e("i", "SendReceiver"+i);
									i++;
								}
								if (BizApp.getInstance().isLocation) {
									ff = true;
									BizApp.getInstance().isLocation = false;
								}
								BizApp.getInstance()
										.getmLocationClient().stop();
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						} else {
							BizApp.getInstance().getmLocationClient()
									.stop();
						}
					}
					if ((BizApp.getInstance().isWiFiActive() || BizApp
							.getInstance().isNetworkAvailable()) && ff) {
						position.lat = BizApp.getInstance().getLat();
						position.lon = BizApp.getInstance().getLon();
					} else {
						position.lat = 0.0;
						position.lon = 0.0;
					}

					position.address = BizApp.getInstance().getAddress();
					position.msgType = 4;
					position.type = 1;
					position.locationMsg = LocationUtils.getInstance()
							.getLocationMsg();
				
					positions.positions.add(position);
					ShutDownSqlHelper psql = new ShutDownSqlHelper();
					psql.open(BizApp.getInstance().getSqlHelper());
					PositionShutDownInfo pinfo = new PositionShutDownInfo();
					pinfo.setVer(gson.toJson(body));
					pinfo.setPos(gson.toJson(positions));
					pinfo.setType(3);
					psql.addAttribute(pinfo);
				};
			}.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
		// Log.e("isEndo", String.valueOf(isEndo));
	}

	private boolean checkSheetTime() {
		try {
			PositionSqlHelper psql = new PositionSqlHelper();
			psql.open(BizApp.getInstance().getSqlHelper());
			PositionAttributeInfo inf = psql.getAttribute();

			int week = 0;
			int hour = 0;
			int min = 0;
			if (inf != null) {
				ContentResolver cv = BizApp.getInstance().getContentResolver();
				String strTimeFormat = android.provider.Settings.System
						.getString(cv,
								android.provider.Settings.System.TIME_12_24);
				Calendar c = Calendar.getInstance();
				week = c.get(Calendar.DAY_OF_WEEK) - 1;

				hour = c.get(Calendar.HOUR_OF_DAY);
				min = c.get(Calendar.MINUTE);

				if (hour > 24)
					hour = hour - 12;

				String sheet = inf.sheet;

				int dur = inf.getDur() * 1000;

				// Log.e("sheet", sheet);
				String[] sheets = sheet.split(";");
				for (int i = 0; i < sheets.length; i++) {
					String weeks = sheets[i];
					String[] weekc = weeks.split(",");
					if (week == Integer.valueOf(weekc[0])) {
						if (Integer.valueOf(weekc[1]) == 1) {
							if (weekc.length == 2) {
								return true;
							}
							if (weekc.length == 6) {
								// return true;
								long ab = getMill(weekc[2], weekc[3])
										- StringUtil.FormDateTomill(StringUtil
												.getReportTime());
								if (Math.abs(ab) < dur) {
									start = true;
								}
								long ac = getMill(weekc[4], weekc[5])
										- StringUtil.FormDateTomill(StringUtil
												.getReportTime());
								if (Math.abs(ac) < dur) {
									end = true;
								}
								if (hour > Integer.valueOf(weekc[2])
										&& (hour < Integer.valueOf(weekc[4]) || hour == Integer
												.valueOf(weekc[4])
												&& min <= Integer
														.valueOf(weekc[5]))) {
									return true;
								}
								if (hour == Integer.valueOf(weekc[2])
										&& min >= Integer.valueOf(weekc[3])
										&& (hour < Integer.valueOf(weekc[4]) || hour == Integer
												.valueOf(weekc[4])
												&& min <= Integer
														.valueOf(weekc[5]))) {

									return true;
								}
							}
							if (weekc.length == 10) {
								// return true;
								long ab = getMill(weekc[2], weekc[3])
										- StringUtil.FormDateTomill(StringUtil
												.getReportTime());
								if (Math.abs(ab) < dur) {
									start = true;
								}
								long ac = getMill(weekc[4], weekc[5])
										- StringUtil.FormDateTomill(StringUtil
												.getReportTime());
								if (Math.abs(ac) < dur) {
									end = true;
								}
								long ad = getMill(weekc[6], weekc[7])
										- StringUtil.FormDateTomill(StringUtil
												.getReportTime());
								if (Math.abs(ad) < dur) {
									start = true;
								}
								long ae = getMill(weekc[8], weekc[9])
										- StringUtil.FormDateTomill(StringUtil
												.getReportTime());
								if (Math.abs(ae) < dur) {
									end = true;
								}
								if (hour > Integer.valueOf(weekc[2])
										&& (hour < Integer.valueOf(weekc[4]) || hour == Integer
												.valueOf(weekc[4])
												&& min <= Integer
														.valueOf(weekc[5]))) {
									return true;
								}
								if (hour == Integer.valueOf(weekc[2])
										&& min >= Integer.valueOf(weekc[3])
										&& (hour < Integer.valueOf(weekc[4]) || hour == Integer
												.valueOf(weekc[4])
												&& min <= Integer
														.valueOf(weekc[5]))) {
									return true;
								}
								if (hour > Integer.valueOf(weekc[6])
										&& (hour < Integer.valueOf(weekc[8]) || hour == Integer
												.valueOf(weekc[8])
												&& min <= Integer
														.valueOf(weekc[9]))) {
									return true;
								}
								if (hour == Integer.valueOf(weekc[6])
										&& min >= Integer.valueOf(weekc[7])
										&& (hour < Integer.valueOf(weekc[8]) || hour == Integer
												.valueOf(weekc[8])
												&& min <= Integer
														.valueOf(weekc[9]))) {
									return true;
								}
							}
						} else {
							return false;
						}
					}
				}
			}
			return false;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	private long getMill(String hour, String min) {
		try {
			String str = StringUtil.getFormTime();
			return StringUtil.FormDateTomill(str + " " + hour + ":" + min);
		} catch (Exception e) {

		}
		return 0;
	}

}